﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.Project.Models;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;
using static Modules.Person.PersonConstants;
using static Modules.Project.ProjectConstants;

namespace Modules.Project.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectInfoRepository : Repository<ProjectInfo, DefaultDbContext>
    {
        private readonly ILogger logger;
        private readonly IApplicationContext applicationContext;
        private readonly IMemoryCache memoryCache;

        public ProjectInfoRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<ProjectInfoRepository> logger,
             IMemoryCache memoryCache)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
            this.applicationContext = applicationContext;
            this.memoryCache = memoryCache;
        }

        public bool ExistsByPrjNum(ProjectInfo projectInfo, int projectId)
        {
            if (string.IsNullOrEmpty(projectInfo.PrjNum))
                return false;
            return DbContext.Exists<ProjectInfo>("prj_num=@0 AND project_id!=@1 AND is_deleted=0", projectInfo.PrjNum, projectId);
        }

        public bool ExistsByPrjNum(ProjectInfo projectInfo)
        {
            if (string.IsNullOrEmpty(projectInfo.PrjNum))
                return false;
            return DbContext.Exists<ProjectInfo>("prj_num=@0 AND is_deleted=0", projectInfo.PrjNum);
        }

        public bool ExistsByPrjCode(ProjectInfo projectInfo, int projectId)
        {
            if (string.IsNullOrEmpty(projectInfo.GgProjectCode))
                return false;
            return DbContext.Exists<ProjectInfo>("gg_project_code=@0 AND project_id!=@1 AND is_deleted=0", projectInfo.GgProjectCode, projectId);
        }

        public bool ExistsByPrjCode(ProjectInfo projectInfo)
        {
            if (string.IsNullOrEmpty(projectInfo.GgProjectCode))
                return false;
            return DbContext.Exists<ProjectInfo>("gg_project_code=@0 AND is_deleted=0", projectInfo.GgProjectCode);
        }

        public bool ExistsProjectInfo(int projectId, int managerId)
        {
            return DbContext.Exists<ProjectInfo>("project_id=@0 AND manager_id=@1 And is_deleted=0", projectId, managerId);
        }

        public bool ExistsProjectNum(string prjNum)
        {
            return DbContext.Exists<ProjectInfo>("prj_num=@0 AND is_deleted=0", prjNum);
        }

        public IPagedList<ProjectInfo> GetProjectInfos(ProjectInfoQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("project.project_id")
                .From("project");
            sql.LeftJoin("manager as b ").On("project.manager_id=b.manager_id");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Where("project.city_code=@0", deptUser.CityCode ?? 0);
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Where("project.area_code=@0", deptUser.AreaCode ?? 0);
                sql.Where("project.industry_type=@0", deptUser.IndustryType);
            }

            #endregion 主管单位数据权限

            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(project.name Like @0 or prj_num Like @0 or build_corp_name Like @0 or b.name like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.CityCode.HasValue)
                sql.Where("city_code=@0", query.CityCode);
            if (query.AreaCode.HasValue)
                sql.Where("area_code=@0", query.AreaCode);
            if (query.CreateManagerId.HasValue)
                sql.Where("create_manager_id=@0", query.CreateManagerId);
            if (query.ManagerId.HasValue)
                sql.Where("project.manager_id=@0", query.ManagerId);
            if (query.AuditStatus.HasValue)
                sql.Where("audit_status=@0", query.AuditStatus);
            if (query.CorpId.HasValue)
                sql.Where("(project.project_id IN(SELECT project_id FROM project_corp WHERE corp_id =@0) OR project.lump_contractor_corp_id=@0)", query.CorpId);
            if (query.CommanderId.HasValue)
                sql.Where("project.project_id IN(SELECT project_id FROM commander_project WHERE commander_id =@0)", query.CommanderId);
            if (query.BuildCorpId.HasValue)
                sql.Where("build_corp_id=@0", query.BuildCorpId);
            if (query.IsRegister.HasValue)
                sql.Where("is_register=@0", query.IsRegister.Value);
            if (query.IndustryType.HasValue)
                sql.Where("industry_type=@0", query.IndustryType.Value);
            sql.Where("project.is_deleted=0");
            sql.OrderBy("project.project_id DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        /// <summary>
        /// 通过上下文获取当前登录者身份信息的管辖项目Id
        /// </summary>
        /// <returns></returns>
        public IEnumerable<int> GetAllProjectIdsByApplicationContext()
        {
            Sql sql = Sql.Builder;
            sql.Select("project.project_id")
                .From("project");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator() && !deptUser.IsRSAdministrator() && !deptUser.IsBankAdministrator())
            {
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Where("project.city_code=@0", deptUser.CityCode ?? 0);
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Where("project.area_code=@0", deptUser.AreaCode ?? 0);
                sql.Where("project.industry_type=@0", deptUser.IndustryType);
            }

            #endregion 主管单位数据权限

            if (applicationContext.CurrentUser is IProjectUser projectUser && projectUser.ProjectId.HasValue)
            {
                sql.Where("project.project_id=@0", projectUser.ProjectId);
            }
            sql.Where("project.is_deleted=0");
            sql.OrderBy("project.project_id DESC");
            return DbContext.FetchFirstColumn<int>(sql);
        }

        public IEnumerable<ProjectInfo> GetProjectInfosByManagerId(int managerId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("ManagerId", managerId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"ProjectInfosByManagerId:{managerId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("project_id")
                .From("project")
                .Where("manager_id=@0", managerId);
                sql.OrderBy("project_id DESC");
                return sql;
            });
        }

        /// <summary>
        /// 获取总承包的下的项目信息
        /// </summary>
        /// <param name="corpId"></param>
        /// <returns></returns>
        public IEnumerable<ProjectInfo> GetProjectInfosByLumpContractorCorpId(int corpId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("LumpContractorCorpId", corpId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"ProjectInfosByLumpContractorCorpId:{corpId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("project_id")
                .From("project")
                .Where("lump_contractor_corp_id=@0", corpId);
                sql.OrderBy("project_id DESC");
                return sql;
            });
        }

        /// <summary>
        /// 获取建设单位的所有项目集合
        /// </summary>
        /// <param name="constructorId"></param>
        /// <returns></returns>
        public IEnumerable<ProjectInfo> GetProjectInfosByConstructorId(int constructorId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("BuildCorpId", constructorId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"ProjectInfosByConstructor:{constructorId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("project_id")
                .From("project")
                .Where("build_corp_id=@0", constructorId);
                sql.OrderBy("project_id DESC");
                return sql;
            });
        }

        public bool UpdateAuditStatus(ProjectInfo data, 项目审核状态 auditStatus, string reason)
        {
            if (data == null)
                return false;
            var sql_update = Sql.Builder;
            sql_update.Append("Update project SET audit_status = @0 and audit_reason=@1 where project_id = @2", auditStatus, reason, data.ProjectId);//局部更新数据库
            int affectCount = DbContext.Execute(sql_update);
            if (affectCount > 0)
            {
                data.AuditReason = reason;
                data.AuditStatus = auditStatus;
                base.OnUpdated(data);//更新内存数据
                return true;
            }
            return false;
        }

        public ProjectInfo? GetProjectInfoByName(string projectName)
        {
            Sql sql = Sql.Builder.Select("project_id").From("project").Where("name=@0", projectName);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        /// <summary>
        /// 通过招标段号获取所有projectInfo
        /// </summary>
        /// <param name="biddingSectionNums"></param>
        /// <returns></returns>
        public IEnumerable<ProjectInfo> GetProjectInfosByBiddingSectionNum(IEnumerable<string> biddingSectionNums)
        {
            Sql sql = Sql.Builder.Select("project_id").From("project").Where("bidding_section_num in (@0)", biddingSectionNums);
            var id = DbContext.Fetch<int>(sql);
            return PopulateEntitiesByEntityIds(id);
        }

        /// <summary>
        /// 查询当前行政区划代码最大序号
        /// </summary>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public ProjectInfo? GetProjectInfoByMaxSerialNumber(int areaCode, DateTime time)
        {
            Sql sql = Sql.Builder.Select("project_id").From("project").Where("area_code=@0", areaCode);
            sql.Where("DATE(create_time)=@0", time.Date);
            sql.OrderBy("serial_number desc");
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        public IEnumerable<ProjectInfo> GetProjectInfosByStatus(项目状态 status)
        {
            Sql sql = Sql.Builder
               .Select("project_id")
               .From("project")
               .Where("prj_status=@0", status);
            sql.Where("audit_status=@0", 项目审核状态.通过);
            sql.OrderBy("project_id DESC");

            var ids = DbContext.FetchFirstColumn<int>(sql);

            return PopulateEntitiesByEntityIds(ids);
        }

        public int GetProjectIdByPrjNum(string prjNum)
        {
            Sql sql = Sql.Builder.Select("project_id").From("project").Where("prj_num=@0", prjNum);
            return DbContext.FirstOrDefault<int>(sql);
        }

        public ProjectInfo? GetProjectInfoByPrjNum(string prjNum)
        {
            var id = GetProjectIdByPrjNum(prjNum);
            if (id == 0)
                return null;
            return Get(id);
        }

        /// <summary>
        /// 获取首页统计缓存key
        /// </summary>
        /// <param name="deptUser"></param>
        /// <param name="projectUser"></param>
        /// <returns></returns>
        private string GetHomeStatisticCacheKey(IDeptUser? deptUser, IProjectUser? projectUser)
        {
            if (deptUser != null)
            {
                return $"HomeStatisticByDeptId:{deptUser.Id}";
            }
            if (projectUser != null)
            {
                return $"HomeStatisticByProjectId:{projectUser.ProjectId}";
            }
            return "HomeStatisticByAdmin";
        }

        public HomeStatistic GetHomeStatistic()
        {
            var deptUser = applicationContext.CurrentUser as IDeptUser;
            var projectUser = applicationContext.CurrentUser as IProjectUser;
            var cacheKey = GetHomeStatisticCacheKey(deptUser, projectUser);
            var statistic = memoryCache.Get<HomeStatistic>(cacheKey);
            if (statistic != null) return statistic;

            #region 在册工人总数 PersonCount

            var tableSql = "select COUNT(DISTINCT project_group_member.person_id)  as PersonCount from project_group_member   INNER JOIN person  ON  project_group_member.person_id=person.person_id";

            //权限范围
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql += $"  INNER JOIN  project as prj on project_group_member.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql += $" where project_group_member.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion 在册工人总数 PersonCount

            #region PersonXZCount 西藏籍工人总数

            var tableSql2 = "select COUNT(DISTINCT project_group_member.person_id)  as PersonXZCount from project_group_member   INNER JOIN person  ON  project_group_member.person_id=person.person_id";

            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql2 += $"  INNER JOIN  project as prj on project_group_member.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";

                tableSql2 += $" where person.nation='藏'";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql2 += $" where project_group_member.project_id ={projectUser.ProjectId} and person.nation='藏'";
                }
            }

            #endregion PersonXZCount 西藏籍工人总数

            #region NumberAttendees，ActualAttendance 应考勤人数，实际考勤人数

            var tableSql3 = $"select SUM(number_attendees) AS NumberAttendees,SUM(actual_attendance) AS ActualAttendance from report_project_group_days ";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql3 += $"   INNER JOIN  project as prj on report_project_group_days.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
                tableSql3 += $" where report_project_group_days.date='{DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")}'";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql3 += $" where report_project_group_days.project_id ={projectUser.ProjectId} and report_project_group_days.date='{DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")}'";
                }
            }

            #endregion NumberAttendees，ActualAttendance 应考勤人数，实际考勤人数

            #region ManagerCount 现场管理人数

            var tableSql4 = $"select COUNT(DISTINCT project_group_member.person_id) AS ManagerCount from project_group_member ";
            tableSql4 += $"   INNER JOIN person on  project_group_member.person_id=person.person_id ";

            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql4 += $"   INNER JOIN  project as prj on project_group_member.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
                tableSql4 += $" where  project_group_member.is_manager=1";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql4 += $" where project_group_member.project_id ={projectUser.ProjectId} and project_group_member.is_manager=1";
                }
            }

            #endregion ManagerCount 现场管理人数

            #region SuperviseCount 总监理工程师人数

            var tableSql5 = $"select COUNT(DISTINCT project_group_member.person_id) AS SuperviseCount from project_group_member ";
            tableSql5 += $"   INNER JOIN person on  project_group_member.person_id=person.person_id ";

            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql5 += $"   INNER JOIN  project as prj on project_group_member.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
                tableSql5 += $" where  project_group_member.post_category={(int)管理岗位类型.总监理工程师}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql5 += $" where project_group_member.project_id ={projectUser.ProjectId} and project_group_member.post_category={(int)管理岗位类型.总监理工程师}";
                }
            }

            #endregion SuperviseCount 总监理工程师人数

            #region OnlinePaymentAmount，OfflinePaymentAmount，IncomeAmount 工资线上代发，线下代发，进账

            var tableSql6 = $"select SUM(online_payment_amount) AS OnlinePaymentAmount,SUM(offline_payment_amount) AS  OfflinePaymentAmount,SUM(income_amount) AS IncomeAmount from project_special_account_statistic ";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql6 += $"   INNER JOIN  project as prj on project_special_account_statistic.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql6 += $" where project_special_account_statistic.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion OnlinePaymentAmount，OfflinePaymentAmount，IncomeAmount 工资线上代发，线下代发，进账

            #region BankAccountBalance 专户余额

            var tableSql7 = $"select SUM(balance) AS BankAccountBalance from project_special_account ";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql7 += $"   INNER JOIN  project as prj on project_special_account.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql7 += $" where project_special_account.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion BankAccountBalance 专户余额

            #region PaymentPersonCount 工资代发人次

            var tableSql8 = $"select SUM(number_proxy_recipients) AS  PaymentPersonCount from report_project_month ";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql8 += $"   INNER JOIN  project as prj on report_project_month.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql8 += $" where report_project_month.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion PaymentPersonCount 工资代发人次

            #region ContractCount 合同总数（已签订合同人次）

            var tableSql9 = $"select COUNT(person_corp_contract.id) AS ContractCount from person_corp_contract ";
            tableSql9 += $"   INNER JOIN project_group_member on person_corp_contract.person_id=project_group_member.person_id";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql9 += $"   INNER JOIN  project as prj on project_group_member.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql9 += $" where project_group_member.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion ContractCount 合同总数（已签订合同人次）

            #region SignPersonCount 已签订合同人数

            var tableSql11 = $"select COUNT(DISTINCT person_corp_contract.person_id) AS SignPersonCount from person_corp_contract ";
            tableSql11 += $"   INNER JOIN project_group_member on person_corp_contract.person_id=project_group_member.person_id";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql11 += $" INNER JOIN  project as prj on project_group_member.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql11 += $" where project_group_member.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion SignPersonCount 已签订合同人数

            #region GuaranteeBalance 保证金

            var tableSql10 = $"select SUM(balance) AS GuaranteeBalance from project_guarantee_payment ";
            if (deptUser != null)
            {
                string append = "";
                if (deptUser.Level == AdministrativeLevel.City)
                    append = $" and prj.city_code={deptUser.CityCode}";
                if (deptUser.Level == AdministrativeLevel.Area)
                    append = $" and prj.area_code={deptUser.AreaCode}";
                tableSql10 += $"   INNER JOIN  project as prj on project_guarantee_payment.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type={(int)deptUser.IndustryType} {append}";
            }
            if (projectUser != null)
            {
                if (projectUser.ProjectId.HasValue)
                {
                    tableSql10 += $" where project_guarantee_payment.project_id ={projectUser.ProjectId}";
                }
            }

            #endregion GuaranteeBalance 保证金

            var sqlTable = "";
            sqlTable += "(" + tableSql + ") a,";
            sqlTable += "(" + tableSql2 + ") b,";
            sqlTable += "(" + tableSql3 + ") c,";
            sqlTable += "(" + tableSql4 + ") d,";
            sqlTable += "(" + tableSql5 + ") e,";
            sqlTable += "(" + tableSql6 + ") f,";
            sqlTable += "(" + tableSql7 + ") g,";
            sqlTable += "(" + tableSql8 + ") h,";
            sqlTable += "(" + tableSql9 + ") i,";
            sqlTable += "(" + tableSql10 + ") j,";
            sqlTable += "(" + tableSql11 + ") k";
            var sql = Sql.Builder;
            sql.Select("*").From("(" + sqlTable + ")");
            statistic = DbContext.FirstOrDefault<HomeStatistic>(sql);
            memoryCache.Set(cacheKey, statistic, TimeSpan.FromMinutes(3));
            return statistic;
        }
    }
}